import React, { useMemo, useEffect, useRef, useState } from "react";
import { useNavigate, useParams } from "react-router-dom";
import { useRequest, useSize } from "ahooks";
import { NavBar } from "antd-mobile";
import { MoreOutline } from "antd-mobile-icons";
import MessageList from "./MessageList";
import ChatEditor from "./ChatEditor";
import { message_send, chatroom_info } from "@/apis";
import { currentDB } from "@/index";
import { getState } from "@/store";

import * as hm from "@/handle_message";
import styles from "./index.less";
import { BaseInfo, ChatMessage, LogMessage } from "../../../serve/interfaces";

const searchParams = new URLSearchParams(location.search)
const MODE = searchParams.get('mode') as 'normal' | 'no_navbar' | 'no_back' | 'no_more' | 'readonly' || 'normal'
const sameHandle = ["message_send", "chatroom_create", "chatroom_update", "chatroom_delete", "chatroom_adduser", "chatroom_deluser"] as const;

const ChatPage = () => {
  const { loginUser, userMap } = getState();
  const navigate = useNavigate();
  const { id: chatroom_id } = useParams();

  const { data: currentRoomInfo } = useRequest(chatroom_info, { defaultParams: [{ _id: chatroom_id }] });

  const readonly = MODE === 'readonly';
  const show_navbar = MODE != 'no_navbar';
  const show_back = MODE != 'no_back' && !readonly;
  const show_more = MODE != 'no_more' && !readonly;
  const navbar_height = show_navbar ? 45 : 0;
  const operable = readonly ? false : useMemo(() => {
    if (currentRoomInfo) {
      return !currentRoomInfo?.error;
    }
    return false;
  }, [currentRoomInfo]);

  async function recordSeen() {
    const seen_count = await currentDB.log.where({ chatroom_id }).count();
    currentDB.seen_count.put({ chatroom_id, seen_count });
  }

  function mutateNormalMessage(message: ChatMessage & BaseInfo, info: LogMessage & BaseInfo) {
    if (info.chatroom_id != chatroom_id) return
    messageListTarget?.current?.mutate((lastData = { list: [] }) => {
      return { ...lastData, list: [info, ...lastData.list] };
    });
  }

  function mutateRevokelMessage(message: ChatMessage & BaseInfo, info: LogMessage<'message_cancel'> & BaseInfo) {
    if (info.chatroom_id != chatroom_id) return
    messageListTarget?.current?.mutate((lastData = { list: [] }) => {
      return { ...lastData, list: lastData.list.filter(i => {
        return i._id !== info._id
      }).concat(info) };
    });
  }

  useEffect(() => {
    hm.addEventListener("message_send", recordSeen);
    hm.addEventListener("message_cancel", recordSeen);
    for (const ele of sameHandle) {
      hm.addEventListener(ele, mutateNormalMessage);
    }
    hm.addEventListener("message_cancel", mutateRevokelMessage);

    return () => {
      recordSeen();
      hm.removeEventListener("message_send", recordSeen);
      hm.removeEventListener("message_cancel", recordSeen);
      for (const ele of sameHandle) {
        hm.removeEventListener(ele, mutateNormalMessage);
      }
      hm.removeEventListener("message_cancel", mutateRevokelMessage);
    };
  }, []);

  const chatEditorTarget = useRef(null);
  const messageListTarget = useRef(null);

  const size = useSize(chatEditorTarget);

  return (
    <>
      {show_navbar && <NavBar
        className={styles["chat-message-header"]}
        {...(show_back ? {
          back: '返回',
          onBack: () => {
            navigate("/");
          }
        } : {
          backArrow: null
        })}
        back={ show_back && '返回' }

        right={
          show_more && (
            <MoreOutline
              fontSize={36}
              onClick={() => {
                navigate(`/chat_detail/${chatroom_id}`);
              }}
            />
          )
        }
      >
        {currentRoomInfo?.data?.name}
      </NavBar>}
      <MessageList userMap={userMap} loginUser={loginUser} onReply={item => {
        const user = userMap.get(item.message.created_by)
        const input = chatEditorTarget.current?.querySelector('textarea')
        console.log(chatEditorTarget)
        if (input) {
          input.value += `@${user?.name || item.message.created_by} `
        }
      }}
      style={{
        height: `calc(100vh - ${(size?.height | 0) + navbar_height}px)`,
      }}
      chatroom_id={chatroom_id} ref={messageListTarget} />
      <ChatEditor
        disabled={!operable}
        ref={chatEditorTarget}
        onSend={(type, body) => {
          message_send({
            chatroom_id,
            type,
            body,
          });
          messageListTarget?.current?.scrollBottom();
        }}
      />
    </>
  );
};

export default ChatPage;
